<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2018/9/29
 * Time: 14:34
 */
namespace app\lib\exception;
use think\exception\Handle;
use think\Log;
use think\Request;
use Exception;
class ExceptionHandler extends Handle{
    private $code;
    private $msg;
    private $errorCode;
    public function render(Exception $e)
    {
       if($e instanceof BaseException){
            $this->code=$e->code;
            $this->msg=$e->msg;
            $this->errorCode=$e->errorcode;
        }else{
            if(config('app_debug')){
                return parent::render($e);
            }else{
                $this->code=500;
                $this->msg='服务器内部错误';
                $this->errorCode=999;
                $this->recordErrorLog($e);
            }

        }
        $request=Request::instance();
        $result=[
            'msg'=>$this->msg,
            'errorCode'=>$this->errorCode,
            'request_url'=>$request->url(),
        ];
        return json($result,$this->code);
    }
    private function recordErrorLog(Exception $e)
     {
         log::init([
             'type' => 'File',
             'path' => LOG_PATH,
              'level' => ['error']
          ]);
         Log::record($e->getMessage(), 'error');
     }
}

